package com.ecelin;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfReader;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class 合并PDF extends JFrame {
    private DefaultListModel<File> pdfListModel = new DefaultListModel<>();
    private JList<File> pdfList;
    private JButton selectButton;
    private JButton mergeButton;
    private JButton moveUpButton;
    private JButton moveDownButton;
    private JButton removeButton;

    public 合并PDF() {
        setTitle("PDF 合并工具");
        setSize(600, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 创建面板
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());

        // 文件列表
        pdfList = new JList<>(pdfListModel);
        pdfList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        JScrollPane scrollPane = new JScrollPane(pdfList);
        panel.add(scrollPane, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridLayout(5, 1)); // 增加一个按钮，所以需要5行

        // 选择文件按钮
        selectButton = new JButton("选择 PDF 文件");
        selectButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setMultiSelectionEnabled(true);
                fileChooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
                    @Override
                    public boolean accept(File f) {
                        return f.isDirectory() || f.getName().toLowerCase().endsWith(".pdf");
                    }

                    @Override
                    public String getDescription() {
                        return "PDF Files (*.pdf)";
                    }
                });

                // 设置默认目录为用户桌面
                fileChooser.setCurrentDirectory(new File(System.getProperty("user.home") + File.separator + "Desktop"));

                int result = fileChooser.showOpenDialog(合并PDF.this);
                if (result == JFileChooser.APPROVE_OPTION) {
                    File[] selectedFiles = fileChooser.getSelectedFiles();
                    for (File file : selectedFiles) {
                        pdfListModel.addElement(file);
                    }
                    JOptionPane.showMessageDialog(合并PDF.this, "选择了 " + selectedFiles.length + " 个文件", "信息", JOptionPane.INFORMATION_MESSAGE);
                }
            }
        });

        // 上移按钮
        moveUpButton = new JButton("上移");
        moveUpButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int[] selectedIndices = pdfList.getSelectedIndices();
                if (selectedIndices.length > 0 && selectedIndices[0] > 0) {
                    for (int i = 0; i < selectedIndices.length; i++) {
                        File selectedFile = pdfListModel.getElementAt(selectedIndices[i]);
                        pdfListModel.remove(selectedIndices[i]);
                        pdfListModel.insertElementAt(selectedFile, selectedIndices[i] - 1);
                    }
                    pdfList.setSelectedIndices(shiftIndicesDown(selectedIndices));
                }
            }
        });

        // 下移按钮
        moveDownButton = new JButton("下移");
        moveDownButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int[] selectedIndices = pdfList.getSelectedIndices();
                if (selectedIndices.length > 0 && selectedIndices[selectedIndices.length - 1] < pdfListModel.getSize() - 1) {
                    for (int i = selectedIndices.length - 1; i >= 0; i--) {
                        File selectedFile = pdfListModel.getElementAt(selectedIndices[i]);
                        pdfListModel.remove(selectedIndices[i]);
                        pdfListModel.insertElementAt(selectedFile, selectedIndices[i] + 1);
                    }
                    pdfList.setSelectedIndices(shiftIndicesUp(selectedIndices));
                }
            }
        });

        // 移除按钮
        removeButton = new JButton("移除选中的 PDF 文件");
        removeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int[] selectedIndices = pdfList.getSelectedIndices();
                if (selectedIndices.length == 0) {
                    JOptionPane.showMessageDialog(合并PDF.this, "请选择要移除的 PDF 文件", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                // 从后往前删除，避免索引变化问题
                for (int i = selectedIndices.length - 1; i >= 0; i--) {
                    pdfListModel.remove(selectedIndices[i]);
                }

                // 重新选择一个文件（如果有）
                if (pdfListModel.getSize() > 0) {
                    if (selectedIndices[0] < pdfListModel.getSize()) {
                        pdfList.setSelectedIndex(selectedIndices[0]);
                    } else {
                        pdfList.setSelectedIndex(selectedIndices[0] - 1);
                    }
                }
            }
        });

        // 合并按钮
        mergeButton = new JButton("合并 PDF 文件");
        mergeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (pdfListModel.getSize() == 0) {
                    JOptionPane.showMessageDialog(合并PDF.this, "请先选择 PDF 文件", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                JFileChooser saveFileChooser = new JFileChooser();
                saveFileChooser.setDialogTitle("保存合并后的 PDF 文件");
                saveFileChooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
                    @Override
                    public boolean accept(File f) {
                        return f.isDirectory() || f.getName().toLowerCase().endsWith(".pdf");
                    }

                    @Override
                    public String getDescription() {
                        return "PDF Files (*.pdf)";
                    }
                });
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                saveFileChooser.setSelectedFile(new File("合并" + sdf.format(new Date()) + ".pdf")); // 默认文件名

                // 设置默认目录为用户桌面
                saveFileChooser.setCurrentDirectory(new File(System.getProperty("user.home") + File.separator + "Desktop"));

                int result = saveFileChooser.showSaveDialog(合并PDF.this);
                if (result == JFileChooser.APPROVE_OPTION) {
                    File selectedFile = saveFileChooser.getSelectedFile();
                    String outputPath = selectedFile.getAbsolutePath();
                    if (!outputPath.toLowerCase().endsWith(".pdf")) {
                        outputPath += ".pdf";
                    }

                    try {
                        mergePdfs(pdfListModel, outputPath);
                        JOptionPane.showMessageDialog(合并PDF.this, "PDF 文件合并成功，路径: " + outputPath, "成功", JOptionPane.INFORMATION_MESSAGE);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(合并PDF.this, "合并 PDF 文件时出错: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        });

        buttonPanel.add(selectButton);
        buttonPanel.add(moveUpButton);
        buttonPanel.add(moveDownButton);
        buttonPanel.add(removeButton);
        buttonPanel.add(mergeButton);

        panel.add(buttonPanel, BorderLayout.EAST);

        add(panel);
    }

    private void mergePdfs(DefaultListModel<File> pdfListModel, String outputPath) throws DocumentException, IOException {
        Document document = new Document();
        PdfCopy copy = null;
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(outputPath);
            copy = new PdfCopy(document, fos);
            document.open();

            for (int i = 0; i < pdfListModel.getSize(); i++) {
                File file = pdfListModel.getElementAt(i);
                PdfReader reader = null;
                try {
                    reader = new PdfReader(file.getAbsolutePath());
                    int n = reader.getNumberOfPages();
                    for (int page = 1; page <= n; page++) {
                        copy.addPage(copy.getImportedPage(reader, page));
                    }
                } catch (Exception ex) {
                    System.err.println("Error reading PDF file: " + file.getAbsolutePath());
                    ex.printStackTrace();
                } finally {
                    if (reader != null) {
                        reader.close();
                    }
                }
            }
        } finally {
            if (document != null) {
                document.close();
            }
            if (copy != null) {
                copy.close();
            }
            if (fos != null) {
                fos.close();
            }
        }
        System.out.println("Merged PDF saved to: " + outputPath);
    }

    private int[] shiftIndicesDown(int[] indices) {
        int[] newIndices = new int[indices.length];
        for (int i = 0; i < indices.length; i++) {
            newIndices[i] = indices[i] - 1;
        }
        return newIndices;
    }

    private int[] shiftIndicesUp(int[] indices) {
        int[] newIndices = new int[indices.length];
        for (int i = 0; i < indices.length; i++) {
            newIndices[i] = indices[i] + 1;
        }
        return newIndices;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new 合并PDF().setVisible(true);
            }
        });
    }
}
